import socket
import time
import os

# dir_prefix = "./src/test/noisy_test/"
dir_prefix = os.path.dirname(os.path.realpath(__file__))
data_file = open(dir_prefix+"/recv.txt","r",newline='')
data = data_file.read().splitlines()

line_num = 0

def read_next_line():
    global line_num,data
    if line_num>=len(data):
        return "EOF"

    line_str = data[line_num]
    line_num+=1

    line = line_str.split(",")
    
    data_type = line[0]
    legal_data = True
    if data_type == "SENSOR_TYPE":
        for i in range(1,5):
            try:
                p = int(line[i])
            except:
                legal_data=False
    elif data_type == "ACTION_TYPE":
        if (len(line[1])!=1):
            legal_data = False
    elif data_type == "ANGLE_TYPE":
        try:
            p = float(line[1])
        except:
            legal_data=False

    if (legal_data):
        return line_str
    else:
        return "SKIP"

def send_msg(udp_socket):
    ip = '127.0.0.1'
    port = 41234

    init_msg = "0 SYSTEM_TYPE,RESET"
    udp_socket.sendto(init_msg.encode("utf-8"), (ip, port))
    # input("pause")

    while True:
        msg = read_next_line()
        print("send> [{}] {}".format(line_num,msg))
        
        # input("pause")
        if (msg=='SKIP'): continue
        send_msg = str(line_num)+" " + msg
        udp_socket.sendto(send_msg.encode("utf-8"), (ip, port))
        time.sleep(0.02)
        # input("pause")
        if (msg=='EOF'):
            break
 
def main():
    udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    send_msg(udp_socket)
 
if __name__ == "__main__":
    main()